// pages/choiceProject/index.js
import axios from '../network/index'
var pageNum;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showClose: false,
    searchText: '',
    list: [],
    spaceText: "加载中...",
    result: [],
    projectCode: '',
    showDetail: false,
    detailList: [],
    totals: '0.00',
    originList: [],
    noMore: false,
    selectArr: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  getTotals() {
    let val = 0
    let selectList = this.data.result
    let list = this.data.selectArr
    let arr = []
    if (selectList && selectList.length > 0) {
      selectList.forEach(item => {
        arr = arr.concat(list.filter(items => item == items.packCode))
      })
    }
    if (arr && arr.length > 0) {
      arr.forEach(items => {
        val += Number(items.amount) * Number(items.num)
      })
    } else {
      val = 0
    }
    this.setData({
      totals: val.toFixed(2)
    })
  },
  prevImg(e) {
    let img = e.currentTarget.dataset.img
    let urls = this.data.detailList.map(item => item.img)
    wx.previewImage({
      current: img,
      urls,
    })
  },
  closeDetail() {
    this.setData({
      showDetail: false,
      detailList: []
    })
  },
  //查看物料组成
  lookMaterials(e) {
    let currentList = e.currentTarget.dataset.child
    console.log(currentList, 'currentList');
    this.setData({
      showDetail: true,
      detailList: currentList
    })
  },
  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  onChange(event) {
    console.log(event.detail, 'event.detail');
    this.setData({
      result: event.detail,
    });
    this.setSelect(event.detail)
    this.getTotals()
  },
  setSelect(list = []) {
    list.forEach(item => {
      this.data.list.forEach(items => {
        if (item == items.packCode) {
          let v = this.data.selectArr.findIndex(itemss => itemss.packCode == item)
          if (v == -1) {
            this.data.selectArr.push(items)
          } else {
            this.data.selectArr[v] = items
          }
        }
      })
    })
  },
  onLoad: function (options) {
    if (options.code) {
      this.setData({
        projectCode: options.code
      })
    }
    pageNum = 1
    this.getMaterialList(pageNum)
  },
  //搜索框事件
  searchIpt(e) {
    this.setData({
      showClose: e.detail.value ? true : false,
      searchText: e.detail.value
    })
    pageNum = 1
    this.getMaterialList(pageNum)
  },
  //清空搜索框内容
  clearSearhText() {
    this.setData({
      searchText: '',
      showClose: false
    })
    this.getMaterialList(pageNum)
  },
  //获取科目列表
  getMaterialList(pageNum, more) {
    axios({
      url: "/api/material/packRecordList",
      method: 'POST',
      data: {
        pageNum,
        pageSize: 10,
        searchVal: this.data.searchText
      }
    }).then(res => {
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
      if (res.code == 200) {
        res.data.content.forEach(item => {
          if (!item.num && item.num != 0) item['num'] = 1
        })
        var arr = this.data.list
        this.setData({
          noMore: res.data.content.length < 10 ? true : false,
          list: more ? arr.concat(res.data.content) : res.data.content,
          spaceText: res.data.content && res.data.content.length > 0 ? '' : '暂无数据',
        })
        this.setCache(this.data.list)
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.msg,
          showCancel: false
        })
      }
    }).catch(() => {
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
    })
  },
  //选择变化事件
  numChange(e) {
    console.log(123, '213123');
    var list = this.data.list
    var index = e.currentTarget.dataset.index
    list[index].num = e.detail;
    this.setData({
      list
    })
    wx.setStorageSync('cacheList', list.filter(item => item.num > 0))
    this.setSelect(this.data.result)
    this.getTotals()
  },

  //确认
  confirm() {
    // let cacheList = this.data.list.filter(item => item.num > 0)
    // wx.setStorageSync('cacheList', cacheList)

    let packData = this.data.result.map(item => ({
      packNum: this.data.list.find(items => items.packCode === item).num,
      packCode: item
    }))
    axios({
      url: "/api/project/addProjectMaterialPack",
      method: 'POST',
      data: {
        packData,
        projectCode: this.data.projectCode
      }
    }, 'application/json').then(res => {
      if (res.code == 200) {
        wx.removeStorageSync('cacheList')
        wx.showToast({
          title: res.msg,
          duration: 800,
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 800);

      }
    })

  },
  //载入缓存
  setCache(list = []) {
    var _this = this
    let cacheList = wx.getStorageSync('cacheList')
    list.forEach(item => {
      cacheList.forEach(items => {
        if (items.packCode == item.packCode) {
          item.num = items.num
        }
      })
    })
    _this.setData({
      list
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorageSync('cacheList')
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
    this.onLoad()

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.noMore) {
      wx.showToast({
        title: '没有更多数据了',
        icon: "none"
      })
      return
    }
    pageNum += 1
    this.getMaterialList(pageNum, true)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})